<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input v-model.trim="query.productNo" clearable placeholder="产品编号" @keyup.enter.native="search" />
      <el-input v-model.trim="query.productName" clearable placeholder="产品名称" @keyup.enter.native="search" />
      <el-select v-model="query.itype" clearable placeholder="类型">
        <el-option v-for="item in itypes" :key="item.key" :label="`${item.displayName}`" :value="item.key" />
      </el-select>
      <el-select v-model="query.istatus" clearable placeholder="状态">
        <el-option v-for="item in search_status" :key="item.key" :label="`${item.displayName}`" :value="item.key" />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="search">{{ $t('table.search') }}</el-button> -->
      <el-button style="margin-left: 0;" type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
    </div>
    <el-table :data="tableData" row-key="id" highlight-current-row border
      :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
      <el-table-column prop="bankName" label="开户行" width="160" />
      <el-table-column prop="bankAccount" label="银行账号" />
      <el-table-column prop="beneficiaryAccountName" label="收款账号名称" width="160" />
      <el-table-column prop="amount" label="银行金额" />
      <el-table-column prop="state" label="状态">
        <template slot-scope="{row:{state}}">
          <el-tag :type="state == 1 ? 'success' : 'danger'">{{ state == 1 ? '启用' : '停用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" prop="creator" />
      <el-table-column label="创建时间" prop="createTime" width="160" />
      <el-table-column label="更新人" prop="updater" />
      <el-table-column label="更新时间" prop="updateTime" width="160" />
      <el-table-column width="490" :label="$t('table.actions')" align="center">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">{{ $t('table.edit') }}</el-button>
          <el-button type="primary" size="mini" @click="handelPrepare(row)">预收/预付</el-button>
          <el-button type="primary" size="mini" @click="handelClick(0, row)">新增资金变动</el-button>
          <el-button type="primary" size="mini" @click="handelClick(1, row)">资金变动明细</el-button>
          <el-button size="mini" type="danger" :disabled="row.amount" @click="handleDelete(row, $index)">{{
            $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
      @pagination="getInfo" />
    <el-dialog @closed="handleClose" :close-on-click-modal="false" :visible.sync="dialogVisible"
      :title="product.id ? '编辑' : '新增'">
      <el-form ref="ruleForm" :model="product" label-width="110px" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="开户行" prop="bankName">
              <el-input v-model.trim="product.bankName" placeholder="请输入开户行名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="bankAccount">
              <el-input v-model.trim="product.bankAccount" placeholder="请输入银行账号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="收款账号名称" prop="beneficiaryAccountName">
              <el-input v-model.trim="product.beneficiaryAccountName" placeholder="请输入收款账号名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="product.state" size="small">
                <el-radio-button v-for="state in status" :key="state.key" :label="state.key">
                  {{ state.displayName }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="dialogVisible = false">{{ $t('permission.cancel') }}</el-button>
        <el-button type="primary" @click="confirm">{{ $t('permission.save') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog width="70%" @closed="fundHandleClose" :close-on-click-modal="false" :visible.sync="fundDialogVisible"
      :title="fundIsDetails ? '资金变动明细' : '新增资金变动'">
      <el-form v-show="!fundIsDetails" ref="fundRuleForm" :model="fund" label-width="110px" :rules="fundRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="收入/支付" prop="type">
              <el-select style="width: 100%;" v-model="fund.type" clearable placeholder="请选择收入/支出"
                @change="handleChange">
                <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收支项目" prop="subjectId">
              <el-select style="width: 100%;" :disabled="!fund.type" v-model="fund.subjectId" clearable
                placeholder="请选择收支项目">
                <el-option v-for="item in subjectList" :key="item.id" :label="item.subjects" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input v-model.trim="fund.amount" onkeyup="value=value.replace(/[^\d.]/g,'')" placeholder="请输入金额" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table v-show="fundIsDetails" :data="fundTableData" row-key="id" highlight-current-row border
        :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
        <el-table-column prop="subjectType" label="收入/支出" />
        <el-table-column prop="subjectName" label="科目" />
        <el-table-column prop="orderNumber" label="订单号" width="160" />
        <el-table-column prop="invoiceCode" label="发票号" />
        <el-table-column prop="amount" label="金额" />
        <el-table-column prop="paymentMethod" label="付款方式" />
        <el-table-column prop="imageUrl" label="水单">
          <template slot-scope="{row:{imageUrl}}">
            <el-image v-if="imageUrl" :src="`${VUE_APP_BASE_API_IMG}/${imageUrl}`" :preview-src-list="[`${VUE_APP_BASE_API_IMG}/${imageUrl}`]"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="creator" />
        <el-table-column label="创建时间" prop="createTime" width="160" />
      </el-table>
      <pagination style="padding: 0;" v-show="fundIsDetails && fundTotal > 0" :total="fundTotal"
        :page.sync="fundQuery.pageIndex" :limit.sync="fundQuery.pageSize" @pagination="handelClick(1, fundQuery)"
        :pageSizes="[5, 10]" />
      <div slot="footer" class="dialog-footer" v-show="!fundIsDetails">
        <el-button type="danger" @click="fundDialogVisible = false">{{ $t('permission.cancel') }}</el-button>
        <el-button type="primary" @click="fundConfirm">{{ $t('permission.save') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog @closed="prepareHandleClose" :close-on-click-modal="false" :visible.sync="prepareDialogVisible"
      title="预收/预付">
      <el-form ref="prepareRuleForm" :model="prepare" label-width="110px" :rules="prepareRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="预收/预付" prop="type">
              <el-select style="width: 100%;" v-model="prepare.type" clearable placeholder="请选择预收/预付"
                @change="handleType">
                <el-option v-for="item in prepareList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户" prop="partnerId">
              <el-select style="width: 100%;" :disabled="prepare.type == null || prepare.type === ''"
                v-model="prepare.partnerId" clearable placeholder="请选择客户">
                <el-option v-for="item in partnersList" :key="item.id" :label="item.partnerName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="金额" prop="price" clearable>
              <el-input v-model.trim="prepare.price" @input="prepare.price = prepare.price.replace(/[^\d|\.]/g, '')"
                placeholder="请输入金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="prepare.type == 1">
            <el-form-item label="付款方式" prop="paymentMethod" clearable>
              <el-input v-model.trim="prepare.paymentMethod" placeholder="请输入付款方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上传水单" prop="file">
              <el-upload class="elUpload" ref="elUpload" accept="*" drag :auto-upload="false" action="#"
                :on-change="handleChangeFile" :on-remove="handleRemove" :limit="1">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png/pdf文件</div> -->
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="prepareDialogVisible = false">{{ $t('permission.cancel') }}</el-button>
        <el-button type="primary" @click="prepareConfirm">{{ $t('permission.save') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { accountPageList, accountAdd, accountModify, accountDel, accAccountSaveDetails, accAccountGetDetails, accAddReceive, accAddPay } from '@/api/product'
import { codePartnersGetAll } from '@/api/invoice'
import { accSubjectsGetAll } from '@/api/turngroupRela'
import { parseTime } from '@/utils'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { deepClone, Compare, isObjectEqual } from '../../../utils'

const product = {
  state: 1
}
const _detail = {
  // id: null,
  linecode: '',
  lineType4List: ''
}

export default {
  name: 'Product',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      VUE_APP_BASE_API_IMG:process.env.VUE_APP_BASE_API_IMG,
      prepareList: [{
        label: '预收',
        value: 0
      }, {
        label: '预付',
        value: 1
      }],
      types: [{
        label: '收入',
        value: 1
      }, {
        label: '支出',
        value: 2
      }],
      line: [],
      rules: {
        bankName: [
          { required: true, message: '请输入开户行名称', trigger: 'blur' }
        ],
        bankAccount: [
          { required: true, message: '请输入银行账号', trigger: 'blur' }
        ],
        beneficiaryAccountName: [
          { required: true, message: '请输入收款账号名称', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      total: 0,
      product: Object.assign({}, product),
      status: [
        { key: 1, displayName: '启用' },
        { key: 0, displayName: '禁用' }
      ],
      query: {
        pageIndex: 1,
        pageSize: 20
      },
      fundQuery: {
        pageIndex: 1,
        pageSize: 5
      },
      tableData: [],
      fund: {},
      fundDialogVisible: false,
      fundRules: {
        type: [
          { required: true, message: '请选择收入/支出', trigger: 'change' }
        ],
        subjectId: [
          { required: true, message: '请选择收支科目', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入金额', trigger: 'blur' }
        ]
      },
      subjectList: [],
      fundTableData: [],
      fundTotal: 0,
      fundIsDetails: false,
      prepareDialogVisible: false,
      prepare: {},
      prepareRules: {
        type: [
          { required: true, message: '请选择预收/预付', trigger: 'change' }
        ],
        partnerId: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入金额', trigger: 'blur' }
        ],
        paymentMethod: [
          { required: true, message: '请输入付款方式', trigger: 'blur' }
        ],
        file: [

        ]
      },
      partnersList: []
    }
  },
  mounted() {
    this.getInfo()
  },
  methods: {
    handleChangeFile(file, fileList) {
      this.prepare.file = file.raw;
    },
    handleRemove() {
      this.prepare.file = "";
    },
    fundHandleClose() {
      this.fund = {}
      this.$refs['fundRuleForm'].resetFields();
    },
    handleType() {
      this.getCodePartnersGetAll()
    },
    async getCodePartnersGetAll() {
      this.partnersList = await codePartnersGetAll({
        type: (this.prepare.type + 1).toString()
      })
    },
    fundConfirm() {
      this.$refs['fundRuleForm'].validate(async (valid) => {
        if (valid) {
          await accAccountSaveDetails(this.fund)
          this.getInfo()
          this.fundDialogVisible = false
          this.$message.success('操作成功！')
        }
      })
    },
    async handleChange(e) {
      this.$set(this.fund, 'subjectId', '')
      this.subjectList = await accSubjectsGetAll({
        type: e
      })
    },
    prepareHandleClose() {
      this.prepare = {}
      this.$refs['prepareRuleForm'].resetFields();
      this.$refs["elUpload"].clearFiles();
    },
    prepareConfirm() {
      this.$refs['prepareRuleForm'].validate(async (valid) => {
        if (valid) {
          if (this.prepare.type == 1) {
            const isValidFile = await this.validateFileBeforeUpload(
              this.prepare.file
            );
            if (!isValidFile) {
              // 如果文件验证失败，则显示错误消息并返回
              this.$message.error("上传文件不符合要求，请重新选择！");
              return;
            };
          }

          const formData = new FormData()
          for (let key in this.prepare) {
            if (key !== 'type') {
              formData.append(key, this.prepare[key])
            }
          }
          if (this.prepare.type) {
            await accAddPay(formData)
          } else {
            await accAddReceive(formData)
          }
          this.getInfo()
          this.$message.success('操作成功！')
          this.prepareDialogVisible = false
        }
      })
    },
    async validateFileBeforeUpload(file) {
      try {
        var extension = file.name
          .split(".")
          .pop()
          .toLowerCase();
        const allowedExtensions = ["jpg", "jpeg", "png", "pdf","xls","xlsx"];
        if (!allowedExtensions.includes(extension)) {
          // this.$message({
          //   message: "上传文件只能是.jpg、.jpeg、.png格式!",
          //   type: "warning"
          // });
          return false;
        }
        // 这里可以添加更多的文件验证逻辑，比如文件大小等
        return true;
      } catch (error) {
        console.error("文件验证出错:", error);
        return false;
      }
    },
    async handelPrepare(row) {
      this.prepare.accountId = row.id
      this.prepareDialogVisible = true
    },
    async handelClick(val, item) {
      //0-新增；1-明细
      if (val) {
        this.fundIsDetails = true
        const formData = new FormData()
        this.fundQuery.id = item.id
        for (let key in this.fundQuery) {
          formData.append(key, this.fundQuery[key])
        }
        const { list, total } = await accAccountGetDetails(formData)
        this.fundTableData = list
        this.fundTotal = total
      } else {
        this.fund.accountId = item.id
        this.fundIsDetails = false
      }
      this.fundDialogVisible = true
    },
    handleClose() {
      this.$refs['ruleForm'].resetFields();
    },
    async getInfo() {
      const { items, totalPages } = await accountPageList(this.query)
      this.tableData = items
      this.total = totalPages
    },
    search() {
      this.query.pageIndex = 1
      this.getInfo()
    },
    handleAdd() {
      this.product = Object.assign({}, product)
      this.dialogVisible = true
    },
    handleUpdate(row) {
      this.product = deepClone(row)
      this.dialogVisible = true
    },
    handleDelete(row, $index) {
      this.$confirm('确认删除?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          accountDel(row.id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getInfo()
          })
        })
        .catch(err => console.error(err))
    },
    confirm() {
      const isEdit = !!this.product.id
      if (isEdit) {
        accountModify(this.product).then((res) => {
          this.$message.success('修改成功!')
          this.getInfo()
          this.dialogVisible = false
        })
      } else {
        accountAdd(this.product).then((res) => {
          this.$message.success('新增成功!')
          this.getInfo()
          this.dialogVisible = false
        })
      }
    }
  }
}
</script>
